#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 12 11:42:03 2022

@author: mac1444
"""

import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,3,2,1,3])
y=np.array([14,24,18,17,27])
plt.scatter(x, y, c='r') #确定点的位置和颜色
plt.axis([0,4,0,28]) #确定横纵轴区间
plt.show()
#%%
x_mean = np.mean(x)   #np.mean()是用来计算均值，np.std()是用来计算标准差
y_mean = np.mean(y)
num = 0.0
d = 0.0
for x_i, y_i in zip(x, y): #zip用来打包两个数组构成新的元祖，由元祖组成列表，例如【1，2】，【3，4】组成（1，3，（2，4）
    num += (x_i - x_mean) * (y_i - y_mean)
    d += (x_i - x_mean) ** 2
a = num/d
b = y_mean - a * x_mean
y_hat = a * x + b
plt.scatter(x, y, c='r')
plt.plot(x, y_hat, color='b')
plt.axis([0, 4, 0, 28])
x_predict = 2
y_predict = a * x_predict + b
plt.scatter(x_predict, y_predict, c='g')
plt.show()